package com.lu.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lu.reggie.common.BaseContext;
import com.lu.reggie.common.R;
import com.lu.reggie.dto.OrdersDto;
import com.lu.reggie.entity.OrderDetail;
import com.lu.reggie.entity.Orders;
import com.lu.reggie.entity.User;
import com.lu.reggie.service.IOrderDetailService;
import com.lu.reggie.service.IOrdersService;
import com.lu.reggie.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author 况山云
 * @since 2022-08-22
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private IOrdersService iOrdersService;
    @Autowired
    private IOrderDetailService iOrderDetailService;
    @Autowired
    private IUserService iUserService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据为:{}", orders);
        iOrdersService.submit(orders);
        return R.success("成功下单!");
    }


    /**
     * 用户订单列表
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(Integer page, Integer pageSize) {
        //分页构造器
        Page<Orders> cartPage = new Page(page, pageSize);
        Page<OrdersDto> dtoPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getOrderTime);
        iOrdersService.page(cartPage, queryWrapper);
        List<Orders> records = cartPage.getRecords();
        BeanUtils.copyProperties(cartPage, dtoPage, "records");
        List<OrdersDto> ordersDtoList = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            //订单id
            Long id = item.getId();
            List<OrderDetail> orderDetailList = this.getOrderDetail(id);
            BeanUtils.copyProperties(item, ordersDto);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(ordersDtoList);
        log.info("返回的数据为:{}", dtoPage);
        return R.success(dtoPage);
    }


    /**
     * 通过订单id查询订单集合，避免在stream中遍历的时候直接使用构造条件来查询，防止eq叠加
     * 导致后面查询的数据都是null
     * @param orderId
     * @return
     */
    public List<OrderDetail> getOrderDetail(Long orderId) {
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetails = iOrderDetailService.list(queryWrapper);
        return orderDetails;
    }


    /**
     * 后台订单分页
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> dtoPage = new Page<>(page, pageSize);
        //条件过滤器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //动态模糊查询
        queryWrapper.like(number != null, Orders::getNumber, number)
                .gt(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime)
                .lt(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);
        iOrdersService.page(ordersPage, queryWrapper);
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> dtoRecords = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            Long userId = item.getUserId();
            User user = iUserService.getById(userId);
            if (user != null) {
                //前端用户这个字段对应后端的收货人
                ordersDto.setUserName(item.getConsignee());
            }
            return ordersDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(dtoRecords);
        return R.success(dtoPage);
    }
}
